<?php

namespace app\api\model;

use constant\config;
use think\Model;

class Capital extends Model {
    protected $table = 'capital';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'crtime';            //数据添加的时候，create_time 这个字段不自动写入时间戳
    protected $updateTime = false;
    public static $snakeAttributes = false;
    
    public function specsList() {
        return $this->hasMany('capital_value', 'capital_id')->field('title as option_value_title,option_value_id,capital_id,conditionss,price,artificial');
    }  
    
    
    public function newlyAdded($list, $v, $increment, $k, $envelopes_id = 0, $isFou) {
        
        $signed = 1;
        if ($increment == 1) {
            $signed = 0;
//            $enable=0;
        
        }
        $increment_adopt = 0;
        if ($v['enable'] == 1 && $increment == 1) {
            $increment_adopt = time();
        }
        if (isset($v['giveType']) && $v['giveType'] == 2) {
            $list['give_to_money'] = $list['sum'] * $v['fang'];
            if ($isFou == 1) {
                $list['give_to_money'] = $list['give_to_money'] + $list['small_order_fee'];
            }
        }
        if (isset($v['fixedPrice']) && $v['fixedPrice'] != 0) {
            $list['labor_cost_price'] = $v['fixedPrice'];
        }
        $isMerge = 0;
        if (isset($v['isMerge']) && $v['isMerge']) {
            $isMerge = 1;
        }
        $mergeTag = isset($v['mergeTag']) ? $v['mergeTag'] : 0;
        if (!empty($mergeTag)) {
            $pf       = json_decode(explode('|', $mergeTag)[1], true);
            $mergeTag = explode('|', $mergeTag)[0] . '|' . json_encode(array_merge(array_unique($pf)));
        }
        $list['toPrice']          = (string)round($list['toPrice'], 2);
        $list['labor_cost_price'] = round($list['labor_cost_price'], 2);
        if (isset($v['capital_id']) && $v['capital_id'] != 0) {
            $this->Update(['square' => $v['fang'],//方量
                'un_Price' => $list['sum'],//单价
                'artificial' => $v['artificial'],
                'rule' => $v['sectionTitle'],
                'mast_rule' => $list['mast_rule'],
                'fen' => 4,
                'zhi' => $v['zhi'],
                'groupss' => $list['groupss'],
                'base_contract_price'=>$list['base_contract_price'],
                'class_b' => $v['projectTitle'],//三
                'give' => isset($v['giveType']) ? $v['giveType'] : 0,//三
                'projectId' => $v['product_id'],//三
                'to_price' => $list['toPrice'],//总价
                'small_order_fee_square_min' => $list['small_order_fee_square_min'],//总价
                'small_order_fee_square_max' => $list['small_order_fee_square_max'],//总价
                'labor_cost' => round($list['sumMast'] * $v['fang'], 2),//三
                'enable' => $v['enable'],//三
                'categoryName' => $v['categoryName'], 'labor_cost_price' => $list['sumMast'],//三
                'base_cost' => $list['base_cost'],//三
                'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '', 'products' => isset($v['products']) ? $v['products'] : 0,//三
                'up_products' => isset($v['isGiveUpProducts']) ? $v['isGiveUpProducts'] : 0,//三
                'products_square' => isset($v['products_square']) ? $v['products_square'] : 0,//三
                'products_spec_price' => isset($v['products_spec_price']) ? $v['products_spec_price'] : 0,//三
                'products_id' => isset($v['products_id']) ? $v['products_id'] : 0,//三
                'give_to_money' => isset($list['give_to_money']) ? $list['give_to_money'] : 0,//三
                'is_product_choose' => isset($list['is_product_choose']) ? $list['is_product_choose'] : 0,//三
                'labor_cost_material' => !empty($list['labor_cost_material']) ? $list['labor_cost_material']*$v['fang'] : 0,//三
//                'products_v2_spec' => isset($list['products_v2_spec']) ? $list['products_v2_spec'] : 0,//三
                'mergePrice' => $v['prices'],//三
                'mergeTag' => $mergeTag,//三
                'isMerge' => $isMerge,//三
                'mergeCoefficient' => isset($v['mergeCoefficient']) ? $v['mergeCoefficient'] : 0,//三
                'warranty_years' => $list['warrantYears'],//三
                'warranty_reason' => $list['warrantyReason'],//三
                'small_order_fee' => $list['small_order_fee'],//三
                'settlement_method'=>$list['settlement_method'],
                'fixed_rate'=>$list['fixed_rate'],
                 'fixed_cost'=>$list['fixed_cost'],
                'sort' => $k,], ['capital_id' => $v['capital_id'], 'envelopes_id' => $envelopes_id]);
            $id = $v['capital_id'];
            
        } else {
            $id = $this->insertGetId(['company' => $v['unit'],//单位
                'categoryName' => $v['categoryName'], 'mast_rule' => $list['mast_rule'],//规则
                'square' => $v['fang'],//方量
                'base_contract_price'=>$list['base_contract_price'],
                'un_Price' => $list['sum'],//单价
                'rule' => $v['sectionTitle'],//规则
                'zhi' => $v['zhi'],//质保
                'artificial' => $v['artificial'],//质保
                'base_cost' => $list['base_cost'],//三
                'crtime' => time(),//质保
                'groupss' => $list['groupss'],
                'signed' => $signed,//质保
                'types' => 1,//状态
                'unit_volume' => $v['unit_volume'],//状态
                'increment_per_unit_volume' => $v['increment_per_unit_volume'],//状态
                'labor_cost_material' => !empty($list['labor_cost_material']) ? $list['labor_cost_material']*$v['fang'] : 0,//三
                'fen' => $v['types'],//状态
                'increment' => $increment,//状态
                'to_price' => $list['toPrice'],//总价
                'ordesr_id' => $list['order_id'], 'class_a' => $list['categoryTitle'],//三
                'class_b' => $v['projectTitle'],//三
                'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '', 'small_order_fee_square_min' => $list['small_order_fee_square_min'],//总价
                'small_order_fee_square_max' => $list['small_order_fee_square_max'],//总价
                'enable' => $v['enable'],//三
                'programme' => 1,//三
                'projectId' => $v['product_id'],//三
                'increment_adopt' => $increment_adopt, 'gold_suite' => $v['type'],//三
                'agency' => $v['agency'],//三
                'labor_cost' => round($list['sumMast'] * $v['fang'], 2),//三
                'labor_cost_price' => $list['sumMast'],//三
                'unique_status' => isset($v['unique_status']) ? $v['unique_status'] : 0,//三
                'envelopes_id' => isset($v['envelopes_id']) ? $v['envelopes_id'] : 0,//三
                'products' => isset($v['products']) ? $v['products'] : 0,//三
                'is_product_choose' => isset($list['is_product_choose']) ? $list['is_product_choose'] : 0,//三
                'products_v2_spec' => isset($list['products_v2_spec']) ? $list['products_v2_spec'] : 0,//三
                'up_products' => isset($v['isGiveUpProducts']) ? $v['isGiveUpProducts'] : 0,//三
                'products_spec_price' => isset($v['products_spec_price']) ? $v['products_spec_price'] : 0,//三
                'products_square' => isset($v['products_square']) ? $v['products_square'] : 0,//三
                'products_id' => isset($v['products_id']) ? $v['products_id'] : 0,//三
                'uniqueNumber' => isset($v['uniqueNumber']) ? $v['uniqueNumber'] : 0,//三
                'give' => isset($v['giveType']) ? $v['giveType'] : 0,//三
                'give_to_money' => isset($list['give_to_money']) ? $list['give_to_money'] : 0,//三
                'mergePrice' => $v['prices'],//三
                'mergeTag' => $mergeTag,//三
                'isMerge' => $isMerge,//三
                'mergeCoefficient' => isset($v['mergeCoefficient']) ? $v['mergeCoefficient'] : 0,//三
                'warranty_years' => $list['warrantYears'],//三
                // 'warranty_start_time' =>$list['warrantyText1'],//三
                // 'warranty_end_time' =>$list['exoneration'],//三
                'small_order_fee' => $list['small_order_fee'],//三
                'warranty_reason' => $list['warrantyReason'],//三
                'settlement_method'=>$list['settlement_method'],
                'fixed_rate'=>$list['fixed_rate'],
                  'fixed_cost'=>$list['fixed_cost'],
                'sort' => $k,]);
        }
        
        return $id;
    }
    
    public function oldAdded($product_chan, $v, $order_id, $type, $increment) {
        $signed = 1;
        if ($increment == 1) {
            $signed = 0;
        }
        
        $toPrice = round($product_chan['artificial'] * $v['fang'], 2);
        if (isset($v['capital_id']) && $v['capital_id'] != 0) {
            $this->update(['class_b' => $v['projectTitle'],//三
                'square' => $v['fang'],//方量
                'to_price' => $toPrice,//总价
                'projectId' => $v['product_id'],//三
                'gold_suite' => $v['type'],//三
            ], ['capital_id' => $v['capital_id']]);
            $id = $v['capital_id'];
            
        } else {
            $id = $this->insertGetId(['wen_a' => '', 'wen_b' => '', 'wen_c' => '', 'company' => $v['unit'],//单位
                'square' => $v['fang'],//方量
                'un_Price' => $product_chan['artificial'],//单价
                'rule' => $product_chan['rmakes'],//规则
                'zhi' => $v['zhi'],//质保
                'types' => 1,//状态
                'fen' => $type,//状态
                'crtime' => time(),//质保
                'to_price' => $toPrice,//总价
                'ordesr_id' => $order_id, 'class_a' => $v['title'],//三
                'increment' => $increment,//状态
                'signed' => $signed,//质保
                'class_b' => $v['projectTitle'],//三
                'projectRemark' => isset($v['remarks']) ? $v['remarks'] : '', 'enable' => 1,//三
                'programme' => 1,//三
                'projectId' => $v['product_id'],//三
                'gold_suite' => $v['type'],//三
                'agency' => $v['agency'],//三
                'envelopes_id' => isset($v['envelopes_id']) ? $v['envelopes_id'] : 0,//三
            ]);
        }
        
        
        return $id;
    }
    
    
    /*
     * 查询单个基建信息
     */
    public function QueryOne($capital_id) {
        return $this->where('capital_id', $capital_id)->find();
    }
    
    /*
     * 查询是否有代购主材
     */
    public function whetherAgency($list) {
        
        return $this->where($list)->count();
    }
    
    /*
     * 更新小程序分享列表
     */
    public function share($orderId, $envelopes_id) {
        
        $allow = db('allow')->where(['order_id' => $orderId, 'envelopes_id' => $envelopes_id])->find();
        if ($allow) {
            $capitalId = $this->where(['envelopes_id' => $envelopes_id, 'types' => 1])->column('capital_id');
            db('allow')->where('envelopes_id', $envelopes_id)->update(['capital_id' => implode(',', $capitalId)]);
        }
        
    }
    
    /*
     * 价格区间计算
     */
    public function priceSection($price, $artificial, $priceUser, $mastPrice, $square, $unit, $small_order_fee, $fangs) {
        //单价
        $mast = $mastPrice * $square;
        
        $toPrice = $priceUser * $square;
        //乘以方量的单价
        $mast1              = $mastPrice;
        $toPrice1           = $priceUser;
        $role               = '';
        $smallOrderFeePrice = 0;
        
        if (!empty($price)) {
            
            foreach ($price as $k => $value) {
                if ($value->begin <= $square && $value->end > $square) {
                    if ($toPrice * $value->value != 0) {
                        $toPrice  = $toPrice * $value->value;
                        $toPrice1 = $toPrice1 * $value->value;
                        
                    }
                }
            }
        }
        if (!empty($small_order_fee)) {
            foreach ($small_order_fee as $k => $value) {
                if ($value['start'] <= $fangs && $value['end'] > $fangs) {
                    $smallOrderFeePrice = $value['value'];
                }
            }
        }
        if (!empty($artificial)) {
            foreach ($artificial as $item) {
                if ($item->begin <= $square && $item->end > $square) {
                    if ($mast * $item->value != 0) {
                        $role  = $item->begin . '-' . $item->end . $unit . "计价系数*" . $item->value * 100;
                        $mast  = $mast * $item->value;
                        $mast1 = $mast1 * $item->value;
                    }
                    
                }
            }
        }
        
        return [$mast, $toPrice, $mast1, $toPrice1, $role, $smallOrderFeePrice];
    }
    
    /*
     * 主材代购分开算
     */
    public function capitalProfit($order_id, $capital_id, $envelopes_id) {
        
        $cap = db('capital')->where(['types' => 1, 'enable' => 1])->where('give', '<>', 2)->where('products', 0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->field('capital_id,agency,envelopes_id,to_price')->select();
        
        $agency       = [];
        $MainMaterial = [];
        foreach ($cap as $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
            }
            if ($item['agency'] == 0) {
                $MainMaterial[] = $item;
            }
        }
        $ca                                         = db('envelopes')->where('envelopes_id', $envelopes_id)->find();
        $envelopes_product                          = db('envelopes_product')->where('envelopes_id', $envelopes_id)->where('state', 1)->find();
        $list['agencyMoney']                        = sprintf('%.2f', array_sum(array_column($agency, 'to_price')));
        $list['MainMaterialMoney']                  = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price'))) + $envelopes_product['products_spec_price'];
        $list['give_money']                         = $ca['give_money'] - $ca['products_main_discount_money'];
        $list['purchasing_discount']                = $ca['purchasing_discount'] - $ca['products_purchasing_discount_money'];
        $list['products_purchasing_discount_money'] = $ca['products_purchasing_discount_money'];
        $list['products_main_discount_money']       = $ca['products_main_discount_money'];
        $list['main_discount_money']                = $ca['main_discount_money'];
        $list['purchasing_discount_money']          = $ca['purchasing_discount_money'];
        $list['expense']                            = $ca['expense'];
        $list['gong']                               = $ca['gong'];
        $list['purchasing_expense']                 = $ca['purchasing_expense'];
        
        
        return $list;
    }
    
    public function newcapitalProfit($order_id, $capital_id, $envelopes_id, $agencyFind) {
        
        $cap             = db('capital')->where(['types' => 1, 'enable' => 1])->where('products', 0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->field('capital_id,agency,envelopes_id,to_price,settlement_method')->select();
        $deleteItem      = db('capital')->where(['types' => 1, 'enable' => 1, 'give' => 2])->whereIn('ordesr_id', $order_id)->where('capital_id', $capital_id)->value('to_price');
        $deleteItemMoney = empty($deleteItem) ? 0 : $deleteItem;
        $agency          = [];
        $MainMaterial    = [];
        $daiZhiSho=0;
        $zhuZhiSho=0;
        foreach ($cap as $item) {
            if ($item['agency'] == 1) {
                $agency[] = $item;
                if ($item['settlement_method'] == 3 || $item['settlement_method'] == 4) {
                    $daiZhiSho += $item['to_price'];
                }
            }
            if ($item['agency'] == 0) {
                $MainMaterial[] = $item;
                if ($item['settlement_method'] == 3 || $item['settlement_method'] == 4) {
                    $zhuZhiSho += $item['to_price'];
                }
            }
        }
        $list = [];
        $ca   = db('envelopes')->where('envelopes_id', $envelopes_id)->find();
        if ($agencyFind == 0) {
          
            $envelopes_product    = db('envelopes_product')->where('envelopes_id', $envelopes_id)->where('products_main_expense', '<>', 0)->where('state', 1)->find();
            $manNotMandatory      = db('capital')->where(['types' => 1, 'enable' => 1, 'agency' => 0])->where('unique_status', 0)->where('uniqueNumber','>',0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->sum('to_price');
            $zhuZhiSho      += db('capital')->where(['types' => 1, 'enable' => 1, 'agency' => 0])->whereIn('settlement_method',[3,4])->where('uniqueNumber','>',0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->sum('to_price');
            $list['money']        = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price')) + $envelopes_product['products_spec_price'] + $manNotMandatory-$zhuZhiSho);
            $list['preferential'] = $ca['give_money'] - $ca['products_main_discount_money'] - $deleteItemMoney;
            
            
        }
        if ($agencyFind == 1) {
            $envelopes_product    = db('envelopes_product')->where('envelopes_id', $envelopes_id)->where('products_main_expense', 0)->where('state', 1)->find();
            $prNotMandatory       = db('capital')->where(['types' => 1, 'enable' => 1, 'agency' => 1])->where('unique_status', 0)->where('uniqueNumber','>',0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->sum('to_price');
             $daiZhiSho      += db('capital')->where(['types' => 1, 'enable' => 1, 'agency' => 1])->whereIn('settlement_method',[3,4])->where('uniqueNumber','>',0)->whereIn('ordesr_id', $order_id)->where('capital_id', '<>', $capital_id)->sum('to_price');
            $list['money']        = sprintf('%.2f', array_sum(array_column($agency, 'to_price')) + $envelopes_product['products_spec_price'] + $prNotMandatory-$daiZhiSho);
            $list['preferential'] = $ca['purchasing_discount'] - $ca['products_purchasing_discount_money'] - $deleteItemMoney;
            
        }
        
        if ($agencyFind == 4) {
            $list['money']        = sprintf('%.2f', array_sum(array_column($MainMaterial, 'to_price')));
            $list['preferential'] = $ca['give_money'] - $ca['products_main_discount_money'];
        }
        if ($agencyFind == 3) {
            $list['money']        = sprintf('%.2f', array_sum(array_column($agency, 'to_price')));
            $list['preferential'] = $ca['purchasing_discount'] - $ca['products_purchasing_discount_money'];
            
        }
        
        
        return $list;
    }
    /**
     * 增项优惠，管理费平均分配
     * 
     * @param mixed $data
     * @param mixed $give_money
     * @param mixed $purchasin_money
     * @param mixed $order_setting
     * @param mixed $mainMoney
     * @param mixed $money
     * @return array{productsAgencyList: array, productsManList: array}
     */
    public function assemblyAdditions($data, $give_money, $purchasin_money, $order_setting, $mainMoney, $money,$type=0) {
        $capital    = $this->whereIn('capital_id', $data)->select();
        //主合同管理费
        $manManageList    = [];
         //主合同优惠
        $manDiscountList  = [];
        $manGiveDiscountList  = [];
         //代购合同管理费
        $agencyManageList    = [];
         //代购同优惠
        $agencyDiscountList = [];
        $agencyGiveDiscountList  = [];
        $giveZhu    = 0;
        $giveDai    = 0;
       
        foreach ($capital as $item) {
            if ($item['agency'] == 0) {
                $manManageList[] = $item;
                if($item['settlement_method'] != 3 && $item['settlement_method'] != 4 &&  $item['give'] != 2){
                      $manDiscountList[] =  $item;
                }
                if ($item['give'] == 2 ) {
                    $giveZhu += $item['to_price'];
                }
                 if ($item['give'] == 2 ) {
                    $manGiveDiscountList []=  $item;
                }
                
            }
            if ($item['agency'] == 1) {
                $agencyManageList[] = $item;
                if($item['settlement_method'] != 3 && $item['settlement_method'] != 4 &&  $item['give'] != 2){
                    $agencyDiscountList[] =  $item;
                }
                 if ($item['give'] == 2 ) {
                    $agencyGiveDiscountList []=  $item;
                }
                if ($item['give'] == 2 ) {
                   $giveDai += $item['to_price'];
                }
                
            }
        } 
        if($type==0){
           
            $give_money=bcsub($give_money,$giveZhu,2);
            $purchasin_money=bcsub($purchasin_money,$giveDai,2);
        }
        if(empty($manDiscountList)){
            $manDiscountList=$manGiveDiscountList;
        }
        if(empty($agencyDiscountList)){
            $agencyDiscountList=$agencyGiveDiscountList;
        }
         //管理费平摊
       
         $productsManList=$this->processingData($manManageList,$manDiscountList,$give_money,$order_setting['max_expense_rate'],$mainMoney);
         $productsAgencyList=$this->processingData($agencyManageList,$agencyDiscountList,$purchasin_money,$order_setting['max_agent_expense_rate'],$money);
       
        return ['productsAgencyList' =>$productsAgencyList, 'productsManList' =>$productsManList];
    }
    /**
     * 处理分摊数据
     * @param mixed $manageList
     * @param mixed $discountList
     * @param mixed $give_money
     * @param mixed $max_expense_rate
     * @param mixed $mainMoney
     * @return float|int
     */
    public function processingData($manageList=[],$discountList=[],$give_money,$max_expense_rate,$mainMoney){
        $expense_money    = 0;
        if (!empty($manageList)) {
            $expenseProportion = 0;
            $manageUpdateData = [];
            foreach ($manageList as $k => $i) {
                $sub_expense_money = $i['to_price'] * ($max_expense_rate/ 100);
                if ($k == count($manageList) - 1) {
                    $sub_expense_money = $mainMoney - $expenseProportion;
                } else {
                    $expenseProportion += $sub_expense_money;
                }
                $manageUpdateData[] = [
                    'capital_id' => $i['capital_id'],
                    'sub_expense_money' => $sub_expense_money
                ];
                if (!empty($i['uniqueNumber']) && $i['up_products'] == 1) {
                    $expense_money += $sub_expense_money;
                }
            }
            if (!empty($manageUpdateData)) {
                $this->saveAll($manageUpdateData);
            }
        }
        //优惠平摊
        if (!empty($discountList)) {
            $to_price                = array_sum(array_column($discountList, 'to_price'));
            
            $Proportion = 0;
            $give_moneys=0;
            $discountUpdateData = [];
            foreach ($discountList as $k => $i) {
              
                  
                    $sub_discounted_money = 0;
                    if ($to_price != 0) {
                        if ($k == 0) {
                            $give_moneys = $give_money;
                        } 
                        
                        $sub_discounted_money =  bcmul(bcdiv($i['to_price'] , $to_price,2) , $give_moneys, 2);
                    }
    
                    if ($k == count($discountList) - 1) {
                        if ($give_money >= 0) {
                            $sub_discounted_money = $give_money - $Proportion;
                        }
                    } else {
                        $Proportion += $sub_discounted_money;
                    }
                    $discountUpdateData[] = [
                        'capital_id' => $i['capital_id'],
                        'settlement_method' => $i['settlement_method'],
                        'sub_discounted_money' => $sub_discounted_money
                    ];
                
               }
          
            if (!empty($discountUpdateData)) {
                $this->saveAll($discountUpdateData);
            }
        }
        return $expense_money;
    }
    /**
     * 增项套餐一口价优惠平均分配
     * @param mixed $list
     * */
    public function averagePackage($List)
    {
        // 按 agency 字段分组获取数据
        $capital = $this->where('uniqueNumber', $List['uniqueNumber'])->where('unique_status', 1)->select();

        // 初始化分组数组
        $groupedData = [
            0 => [],  // agency = 0 的记录
            1 => []   // agency = 1 的记录
        ];

        // 一次性将数据按 agency 分组
       
        
        foreach ($capital as $item) {
          
            if ($item['agency'] == 0) {
                if ($item['settlement_method'] != 3 && $item['settlement_method']!=4) {
                     $groupedData[0][] = $item;
                }
            }
            if ($item['agency'] == 1) {
                if ($item['settlement_method'] != 3 && $item['settlement_method'] !=4) {
                    $groupedData[1][] = $item;
                }
            }
        }

        // 定义处理分组数据的函数
        $processGroup = function ($items, $totalDiscount) {
            $updateData = [];
            $proportion = 0;
            $count = count($items);

            foreach ($items as $key => $item) {
                
                    if ($key == $count - 1) {
                        // 最后一条记录处理剩余金额
                        $subDiscount = max(0, $totalDiscount - $proportion);
                    } else {
                        // 计算当前记录的折扣金额
                        $subDiscount = round(($item['to_price'] / (array_sum(array_column($items, 'to_price')))) * $totalDiscount, 2);
                        $proportion += $subDiscount;
                    }
    
                    $updateData[] = [
                        'capital_id' => $item['capital_id'],
                        'settlement_method'=>$item['settlement_method'],
                        'products_sub_discounted_money' => $subDiscount
                    ];
                
           
            }

            // 批量更新数据库
            if (!empty($updateData)) {
                $this->saveAll($updateData);
            }
        };
        // 处理 agency = 0 的分组
        
        if (!empty($groupedData[0])) {
            $processGroup($groupedData[0], $List['coutMainMoenyDiscount']);
        }

        // 处理 agency = 1 的分组
        if (!empty($groupedData[1])) {
            $processGroup($groupedData[1], $List['coutMoenyDiscount']);
        }
    }
    public function workingProcedure($orderId = 0, $type = 0, $capital_id = 0, $capitalList = 0) {
        
        $list = $this->field('capital.class_b,capital.projectId,capital.capital_id,if(ifNUll(auxiliary_project_list.completion_time,0)=0,"",FROM_UNIXTIME(auxiliary_project_list.completion_time,"%Y-%m-%d %H:%i:%s")) as completeTime,capital.ordesr_id as orderId,GROUP_CONCAT(DISTINCT app_user.username) as username,
  (CASE
            WHEN (auxiliary_delivery_node.state =0) or (auxiliary_delivery_node.state =2)  THEN 1
             WHEN auxiliary_delivery_node.state is  null THEN  0
             WHEN auxiliary_delivery_node.state =1 THEN  2
             WHEN GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id) is null THEN 3
             WHEN GROUP_CONCAT(DISTINCT app_user.username) is null THEN 4
             
                 ELSE 0 END
              ) as isNodes,
               GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id) as auxiliary_delivery_scheduleId,
               LENGTH(GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id))- LENGTH(REPLACE(GROUP_CONCAT(DISTINCT auxiliary_delivery_schedule.id), ",", ""))+1 as leng,
                LENGTH(GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1 , auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)))- LENGTH(REPLACE(GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1 ,auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)), ",", ""))+1 as adnIdLeng,
                GROUP_CONCAT(DISTINCT if(auxiliary_delivery_node.state=1, auxiliary_delivery_node.auxiliary_delivery_schedul_id,null)) as ss,
        startup.sta_time,
        GROUP_CONCAT(DISTINCT detailed_work_process.work_process_id) as workProcessId, sum(app_user_order_capital.work_time) as work_time')->Join('startup', 'startup.orders_id=capital.ordesr_id', 'left')->Join('auxiliary_project_list', 'auxiliary_project_list.capital_id=capital.capital_id  and auxiliary_project_list.delete_time is null', 'left')->Join('auxiliary_delivery_schedule', 'auxiliary_project_list.id=auxiliary_delivery_schedule.auxiliary_project_list_id  and auxiliary_delivery_schedule.delete_time is null', 'left')->Join('detailed_work_process', 'detailed_work_process.detailed_id=capital.projectId', 'left')->Join('auxiliary_delivery_node', 'auxiliary_delivery_node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'left')->Join('app_user_order_capital', 'app_user_order_capital.capital_id=capital.capital_id and app_user_order_capital.deleted_at is null and `app_user_order_capital`.`order_id` = capital.ordesr_id', 'left')->Join('app_user', 'app_user_order_capital.user_id=app_user.id', 'left')->whereNull('capital.up_products_time')->where(['capital.types' => 1, 'capital.enable' => 1, 'agency' => 0]);
        if ($capital_id != 0) {
            $list->whereNotIn('capital.capital_id', $capital_id);
        }
        
        if ($capitalList != 0) {
            $list->whereIn('capital.capital_id', $capitalList);
        }
        if ($type != 0) {
            $list->where('increment', $type);
        }
        if ($orderId != 0) {
            $list->where('capital.ordesr_id', $orderId);
        }
        return $list->group('capital.capital_id')->select();
        
    }
    
    public function ShowMaterialsCspital($orderId, $value) {
        return $this->where('ordesr_id', $orderId)->whereIn('projectId', $value)->where(['capital.types' => 1, 'capital.enable' => 1])->count();
    }
    
    /*
     * 基建检核
     */
    public function capitalCheck($orderId, $envelopes_id = 0) {
        
        $this->field('
                capital.capital_id as capitalId,
                capital.square,
                capital.agency,
                if(capital.agency=0,capital.labor_cost,0)as zhuLaborCost,
                 capital.base_cost,
                if(capital.agency=1,capital.labor_cost,0) as daiLaborCost,
                if(capital.agency=1,capital.base_cost*capital.square,0) as daiMaterialCost,
                if(capital.agency=0,capital.to_price,0) as main_price,
                 if(capital.agency=1,capital.to_price,0) as agent_price,
                envelopes.envelopes_id,
                order_setting.order_fee,
                envelopes.give_money,
                envelopes.expense,
                envelopes.purchasing_discount,
                envelopes.purchasing_expense,
                envelopes.created_time,
                envelopes.type,
                detailed.material_ratio,
                envelopes.project_title')
            ->join('envelopes', 'envelopes.envelopes_id=capital.envelopes_id')
            ->join('detailed', 'detailed.detailed_id=capital.projectId')
            ->join('order_setting', 'order_setting.order_id=capital.ordesr_id')
//            ->where('capital.types', 1)
            ->whereRaw('if(envelopes.type=1,capital.types=1 and capital.enable=1,capital.types=1)')->where(function ($quer) {
                $quer->where(['products' => 1, 'is_product_choose' => 1])->whereOr('products', 0);
            });
        if ($envelopes_id != 0) {
            $this->where('envelopes.envelopes_id', $envelopes_id);
        }
        $l = $this->where('envelopes.ordesr_id', $orderId)->group('capital.capital_id')->select();
        foreach ($l as $k => $list) {
            $detailed_option_value_material = \db('detailed_option_value_material')->field("group_concat(detailed_option_value_material.invcode) as invcode,
                  CONCAT('[', GROUP_CONCAT(JSON_OBJECT('invcode',detailed_option_value_material.invcode,'option_value_id',detailed_option_value_material.option_value_id,'recommended_quantity',detailed_option_value_material.recommended_quantity,'sum',0) SEPARATOR ','), ']') as  content,
                capital_value.capital_id")->join('capital_value', 'capital_value.option_value_id=detailed_option_value_material.option_value_id', 'left')->group('capital_value.capital_id')->where('capital_value.capital_id', $list['capitalId'])->find();
            $l[$k]['invcode']               = $detailed_option_value_material['invcode'];
            $l[$k]['content']               = $detailed_option_value_material['content'];
            
        }
        return $l;
    }
    
    /*
     * 甘特图
     */
    public function ganttChart($orderId, $envelopes_id = 0) {
        $envelopes        = new Envelopes();
        $enableEnvelopes  = $envelopes->where('envelopes_id', $envelopes_id)->find();
        $capital_listData = [];
        if ($enableEnvelopes->type == 1) {
            $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList'])->where(['envelopes_id' => $envelopes_id])->find();
            
            foreach ($envelopes['CapitalList'] as $k => $o) {
                if (($o['products'] == 1 && $o['products_v2_spec'] != 0 && $o['is_product_choose'] == 1) || $o['products'] == 0) {
                    $capital_listData[] = $o;
                }
            }
            
        } else {
            
            $envelopes = $envelopes->with(['CapitalDatas', 'CapitalDatas.specsList'])->where(['envelopes_id' => $envelopes_id])->find();
            
            foreach ($envelopes['CapitalDatas'] as $k => $o) {
                if (($o['products'] == 1 && $o['products_v2_spec'] != 0 && $o['is_product_choose'] == 1) || $o['products'] == 0) {
                    $capital_listData[] = $o;
                }
            }
            
            
        };
        $list = [];
        foreach ($capital_listData as $k => $item) {
            $list[$k]['categoryName'] = $item['categoryName'];
            $list[$k]['projectTitle'] = $item['projectTitle'];
            $list[$k]['fang']         = $item['square'];
            $list[$k]['unit']         = $item['company'];
            $list[$k]['product_id']   = $item['projectId'];
            $list[$k]['agency']       = $item['agency'];
        }
        return $list;
    }
}
